<template>
  <div class="analyse" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="" :query="query" :isShowCon="false"></date-time>
            <el-button type="primary" class="primary_btn fr find" v-on:click.stop="search">{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
        </div>
      </div>
      <affix :label="title"></affix>
    </div>
    <div :id = "id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                {{$t('report.mailConverNum')}}<br/>
                {{$t('report.mailNum')}}<br/>
                {{$t('report.mailAverDealTime')}}<br/>
                {{$t('report.averageResponseTime')}}
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="tableData" :sum="totalData" :config="headOptions.Config"></report-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import dateTime from '../base/datetime.vue'
  import reportTable from '../base/reportTable.vue'
  import { deepClone, getFormatTimeBySecond } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, searchTime, colorConfigArr } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  export default {
    name: 'mail_report_category',
    data () {
      return {
        loading: false,
        id: 'mail_report_category',
        title: this.$t('report.mailReportCategory'),
        query: {},
        dialogVisible: false,
        serverData: [],
        headOptions: {
          Config: []
        },
        highchartsDefaultOptions: {
          chart: { type: 'column', animation: false },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: { text: this.$t('report.mailReportCategory') },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
            shared: true
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      dateTime,
      reportTable
    },
    computed: {
      tableData () {
        return this.getTableData(this.serverData)
      },
      totalData () {
        return this.getTotalData(this.serverData, this.headOptions)
      },
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.serverData || this.serverData.length === 0) {
          return options
        }

        let headerConfig = this.headOptions.Config || []
        let datas = this.serverData
        let categoriesArray = []
        let seriesArray = []

        headerConfig.forEach(item => {
          if (!item.show) {
            return
          }
          if (item.name === 'categoryName') {
            return
          }
          let serie = { name: item.displayname, data: [], valueName: item.name }
          if (item.name === 'sessionAverageTimeLength' || item.name === 'averageFirstResponseTimeLength') {
            serie.tooltip = { valueSuffix: 's' }
          }
          seriesArray.push(serie)
        })

        for (let i = 0; i < datas.length; i++) {
          categoriesArray.push((datas[i].categoryName))
          for (let j = 0; j < seriesArray.length; j++) {
            seriesArray[j].data.push(datas[i][seriesArray[j].valueName])
          }
        }

        options.xAxis.categories = categoriesArray
        options.series = seriesArray

        return options
      }
    },
    methods: {
      getTableData (serverData) {
        if (!serverData || serverData.length === 0) {
          return []
        }

        let data = deepClone(serverData)
        data.forEach(item => {
          item.sessionAverageTimeLength = getFormatTimeBySecond(item.sessionAverageTimeLength)
          item.averageFirstResponseTimeLength = getFormatTimeBySecond(item.averageFirstResponseTimeLength)
        })

        return data
      },
      getTotalData (serverData, headOptions) {
        if (!serverData || serverData.length === 0) {
          return [{categoryName: this.$t('report.total')}]
        }

        let headerConfig = headOptions.Config || []
        let datas = serverData
        let total = {
          categoryName: this.$t('report.total'),
          sessionTotalTimeLength: 0,
          firstResponseTotalTimeLength: 0,
          responseTotalCount: 0,
          sessionCompleteCount: 0
        }

        for (let i = 0; i < headerConfig.length; i++) {
          for (let j = 0; j < datas.length; j++) {
            if (!isNaN(datas[j][headerConfig[i].name])) {
              if ((headerConfig[i].name in total) === false) {
                total[headerConfig[i].name] = 0
              }
              total[headerConfig[i].name] += datas[j][headerConfig[i].name]
            }
            if (headerConfig[i].name === 'averageFirstResponseTimeLength') {
              total.firstResponseTotalTimeLength += datas[j]['firstResponseTotalTimeLength']
              total.responseTotalCount += datas[j]['responseTotalCount']
            } else if (headerConfig[i].name === 'sessionAverageTimeLength') {
              total.sessionTotalTimeLength += datas[j]['sessionTotalTimeLength']
              total.sessionCompleteCount += datas[j]['sessionCompleteCount']
            }
          }
        }

        // 平均会话时长
        total.sessionAverageTimeLength = total.sessionCompleteCount > 0 ? Math.round(total.sessionTotalTimeLength / total.sessionCompleteCount) : 0
        total.sessionAverageTimeLength = getFormatTimeBySecond(total.sessionAverageTimeLength)
        // 平均首次响应时长
        total.averageFirstResponseTimeLength = total.responseTotalCount > 0 ? Math.round(total.firstResponseTotalTimeLength / total.responseTotalCount) : 0
        total.averageFirstResponseTimeLength = getFormatTimeBySecond(total.averageFirstResponseTimeLength)
        return [total]
      },
      getSearchQueryData () {
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id },
          user: {
            type: this.$store.state.session.user.type,
            moduleUsers: this.$store.state.session.user.moduleUsers
          }
        }
        let query = deepClone(this.query)
        data.query = Object.assign({}, data.query, query)
        return data
      },
      search () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }

        this.loading = true
        this.$store.dispatch('queryMailCategoryReport', data).then((res) => {
          // 表头
          this.headOptions = deepClone(res.tableHeader)

          this.serverData = deepClone(res.data)
          this.loading = false
        })
      },
      exportXlsx () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }

        this.loading = true
        this.$store.dispatch('queryMailCategoryReport', data).then((res) => {
          this.loading = false
          var headOptions = deepClone(res.tableHeader)
          var serverData = deepClone(res.data)
          var sum = []
          if (serverData.length !== 0) {
            sum = this.getTotalData(serverData, headOptions)
          }
          var tableData = this.getTableData(serverData).concat(sum)

          var headers = headOptionsToXlsxHeaders(headOptions.Config)

          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.mailReportCategory') + timeStamp)
        })
      },
      exportXls () {
        let data = {
          Method: 'exportMailCategory',
          Query: {reportType: this.id, user: this.$store.state.session.user._id}
        }
        let query = deepClone(this.query)
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportMailCategoryReport', data)
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.mailReportCategory') + searchTime(this.query), id: this.id})
      }
    },
    beforeMount () {
      this.$nextTick(function () {
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .analyse
    .deploy
      .tip
        margin-left 0
</style>
